package com.sawen.houserent.service;

import com.alibaba.fastjson.JSONObject;
import com.sawen.houserent.bean.City;
import com.sawen.houserent.mapper.CityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class CityRedisServiceImpl implements CityRedisService {
    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public City selectByPrimaryKey(Integer id) {
        //从缓存中获取id
        String key="city_"+id;
        ValueOperations opts = redisTemplate.opsForValue();
        //判断缓存中是否存在
        Boolean hasKey = redisTemplate.hasKey(key);
        if(hasKey){
            String citys =(String)opts.get(key);
            System.out.println(citys);
            //LOGGER.info("this.selectByPrimaryKey():从缓存中获取城市");
            return JSONObject.parseObject(citys,City.class);
        }
        City city=cityMapper.selectByPrimaryKey(id);
        //插入缓存
        String cityStr = JSONObject.toJSONString(city);
        opts.set(key,cityStr,100, TimeUnit.SECONDS);
        return city;
    }
}
